import scrollMonitor from 'scrollmonitor'
import { animateNow, DirectiveModifiers } from './events'

export function animate(
  el: HTMLElement,
  value: any,
  modifiers: DirectiveModifiers
) {
  const { click, hover, enter, enterFully, exit, exitPartially } = modifiers

  const { clickRef } = value

  const elementWatcher =
    enter || enterFully || exit || exitPartially
      ? scrollMonitor.create(el)
      : undefined

  if (typeof value === 'string') {
    value = { classes: value }
  }

  if (clickRef) {
    const { sourceId } = clickRef
    const sourceEl = document.getElementById(sourceId)
    if (sourceEl) {
      sourceEl.addEventListener('click', () => {
        animateNow(el, clickRef, modifiers)
      })
    }
  }

  if (click) {
    el.onclick = () => {
      animateNow(el, value, modifiers)
    }
    return
  }

  if (hover) {
    el.onmouseover = () => {
      animateNow(el, value, modifiers)
    }
    return
  }

  if (enter) {
    elementWatcher?.enterViewport(() => {
      animateNow(el, value, modifiers)
    }, true)
    return
  }

  if (enterFully) {
    elementWatcher?.fullyEnterViewport(() => {
      animateNow(el, value, modifiers)
    }, true)
    return
  }

  if (exit) {
    elementWatcher?.exitViewport(() => {
      animateNow(el, value, modifiers)
    }, true)
    return
  }

  if (exitPartially) {
    elementWatcher &&
      elementWatcher.partiallyExitViewport(() => {
        animateNow(el, value, modifiers)
      }, true)
    return
  }

  animateNow(el, value, modifiers)
}
